import React, { useEffect, useState } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Button, Card, Form, InputNumber, Descriptions, Tag, Select, message,Input  } from 'antd';
import { connect, history } from 'umi';
import Contanst from '@/config/contanst'
import Yuan from '@/utils/Yuan';
import moment from 'moment';
import { transformMemberCard } from '../service';
import db from '@/utils/localstorage';
const FormItem = Form.Item;
const { TextArea } = Input;

const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 5,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 15,
    },
    md: {
      span: 15,
    },
  },
};
const submitFormLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 10,
      offset: 5,
    },
  },
};
const ConvertCard = props => {
  const { dispatch, vipCard, match, allVipCard, salesList } = props;
  const [form] = Form.useForm();
  const [stopCardType, setStopCardType] = useState(2);
  const [dictTypeList, setDictTypeList] = useState(db.get("dictTypeList")['payment_method']);
  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'cubeVipCardOper/getMemberCardInfo',
        payload: {
          cardId: match.params.cardId,
          memberId: match.params.memberId
        }
      })
      dispatch({
        type: 'cubeVipCardOper/fetchAllVipCard',
        payload:{
          cardType: 4
        }
      })
      dispatch({
        type: 'cubeVipCardOper/fetchSalesList',
        payload:{
          userId:db.get("user").userId
        }
      })
    }
  }, []);
  /**
   *  保存
   * @param {*} values 
   */
  const onFinish = async () => {
    const values = await form.validateFields();
    if (values) {
      const hide = message.loading('正在转换');
      try {
        let result = await transformMemberCard({
          cardId: vipCard.cardId,
          memberId: vipCard.memberId,
          ...values
        });
        hide();
        if (result.code == 0) {
          message.success('转换成功，即将跳转');
          history.push(`/vip/center/detail/${vipCard.memberId}`);
          return true;
        } else {
          message.error(result.message);
          return false;
        }
      } catch (error) {
        hide();
        message.error('转换失败，请重试');
        return false;
      }
    }
  }

  /**
   * 停卡期限
   * @param {*} e 
   */
  const onChange = (e) => {
    setStopCardType(e.target.value)
  }


  return <PageHeaderWrapper>
    <Card title="会员卡信息" style={{ marginBottom: 32 }}>
      <Descriptions size="small">
        <Descriptions.Item label="会员"><a onClick={() => go2VipDetail()}>{vipCard.memberName}</a></Descriptions.Item>
        <Descriptions.Item label="会员卡类型">{Contanst.MemberCardTypeMap[vipCard.cardType]}</Descriptions.Item>
        <Descriptions.Item label="会员卡名称">{vipCard.cardName}</Descriptions.Item>
        <Descriptions.Item label="会员卡创建时间">{vipCard.createTime}</Descriptions.Item>
        <Descriptions.Item label="当前状态"><Tag>{Contanst.CardBindStatusMap[vipCard.cardStatus]}</Tag></Descriptions.Item>
        {
          vipCard.cardType == '3' && <>
            <Descriptions.Item label="有效期">{vipCard.periodValidity}</Descriptions.Item>
            <Descriptions.Item label="剩余天数">{vipCard.balance}</Descriptions.Item>
          </>
        }
        {
          vipCard.cardType == '2' && <>
            <Descriptions.Item label="有效期">{vipCard.periodValidity}</Descriptions.Item>
            <Descriptions.Item label="剩余次数">{vipCard.balance}</Descriptions.Item>
          </>
        }
        {
          vipCard.cardType == '1' && <>
            <Descriptions.Item label="有效期">{vipCard.periodValidity}</Descriptions.Item>
            <Descriptions.Item label="剩余金额">{vipCard.balance}</Descriptions.Item>
          </>
        }
        <Descriptions.Item label="累计实收金额"><Yuan>{vipCard.totalMoney}</Yuan></Descriptions.Item>
        <Descriptions.Item label="开卡场馆">{vipCard.venueName}</Descriptions.Item>
        <Descriptions.Item label="备注">{vipCard.zb}</Descriptions.Item>
      </Descriptions>
    </Card>
    <Card title="次卡转换">
      <Form style={{
        marginTop: 8,
      }}
        form={form}
        name="basic"
        initialValues={{
          stopCardType: stopCardType,
          stopCardTime: [moment(), ""]
        }}
      >
        <FormItem
          {...formItemLayout}
          label="转换卡"
          name="transformCardId"
          rules={[
            {
              required: true,
              message: '请选择转换卡',
            },
          ]}
        >
          <Select style={{ width: '100%' }} placeholder="请选择">
            {
              allVipCard && allVipCard.map((item, index) => <Select.Option value={item.cardId} key={index}>{item.cardName}</Select.Option>)
            }
          </Select>
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="转换次数"
          name="transformNum"
          rules={[
            {
              required: true,
              message: '请输入转换次数',
            },
          ]}
        >
          <InputNumber
            placeholder="请输入转换次数"
            min={0}
            max={vipCard.balance}
            style={{ width: '100%' }}
            formatter={value => `${value}次`}
            parser={value => value.replace('次', '')}
          />
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="差额"
          name="amount"
        >
          <InputNumber
            placeholder="请输入差额"
            min={0}
            style={{ width: '100%' }}
            formatter={value => `${value}元`}
            parser={value => value.replace('元', '')}
          />
        </FormItem>
        <Form.Item
          {...formItemLayout}
          label="支付方式"
          name="paymentMethod"
          rules={[{ required: true, message: '请选择支付方式' }]}
        >
          <Select style={{ width: '100%' }} placeholder="请选择">
            {
              dictTypeList && dictTypeList.map((item, index) => <Select.Option key={index} value={item.value}>{item.label}</Select.Option>)
            }
          </Select>
        </Form.Item>
        <FormItem
            {...formItemLayout}
            label="销售人员"
            name="salesStaffId"
            rules={[{ required: true, message: '请选择销售人员' }]}
          >
             <Select style={{ width: '100%' }} placeholder="请选择">
              {
                 salesList&&salesList.map((item,index)=><Select.Option value={item.userId} key={index}>{item.name}</Select.Option>)
              }
            </Select>
          </FormItem>
        <FormItem
            {...formItemLayout}
            label="备注信息"
            name="consumeStatement"
          >
            <TextArea rows={4} placeholder="请输入"/>
          </FormItem>
        <FormItem
          {...submitFormLayout}
          style={{
            marginTop: 32,
          }}
        >
          <Button type="primary" onClick={onFinish}>
            提交
          </Button>
          <Button
            style={{
              marginLeft: 8,
            }}
            onClick={() => window.history.back()}
          >
            返回
          </Button>
        </FormItem>
      </Form>
    </Card>
  </PageHeaderWrapper>
}

export default connect(({ loading, cubeVipCardOper }) => ({
  vipCard: cubeVipCardOper.vipCard,
  allVipCard: cubeVipCardOper.allVipCard,
  salesList: cubeVipCardOper.salesList,
}))(ConvertCard);